package com.fuint.common.web;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Slf4j
//@Component
public class RequestLoggingFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        // 使用 ContentCachingRequestWrapper 包装请求，以便多次读取请求体
        ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(request);
        byte[] requestBody = wrappedRequest.getContentAsByteArray();
        StringBuilder builder = new StringBuilder();
        builder.append("\n").append("Request URL: ").append(wrappedRequest.getRequestURL()).append("\n");
        // Query参数
        Map<String, String[]> parameterMap = wrappedRequest.getParameterMap();
        if (!parameterMap.isEmpty()) {
            builder.append("Query Parameters:\n");
            for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                String paramName = entry.getKey();
                String[] paramValues = entry.getValue();
                for (String paramValue : paramValues) {
                    builder.append(paramName).append(":").append(paramValue).append("\n");
                }
            }
        }
        // 打印请求体
        else if (requestBody.length > 0) {
            String body = new String(requestBody, StandardCharsets.UTF_8);
            builder.append("Request Body:").append(body).append("\n");
        } else {
            builder.append("No Parameters.");
        }
        log.info(builder.toString());

        // 继续执行过滤链
        filterChain.doFilter(wrappedRequest, response);
    }
}